const express = require('express');
const cors = require('cors');
const apiRoutes = require('./api');
const db = require('../database/db');
const { swaggerProxy, localApiProxy } = require('./proxy');

const app = express();
const port = process.env.SERVER_PORT || 3001;

// 更新 CORS 配置
const corsOptions = {
  origin: function(origin, callback) {
    // 在生产环境中允许所有来源
    callback(null, true);
  },
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'],
  exposedHeaders: ['Content-Type', 'Authorization'],
  optionsSuccessStatus: 200
};

// 使用更新后的 CORS 配置
app.use(cors(corsOptions));

// 添加额外的 CORS 头部
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Credentials', 'true');
  next();
});

// 解析 JSON 请求体
app.use(express.json({ limit: '10mb' }));

// 添加调试日志
app.use((req, res, next) => {
  console.log('Incoming request:', {
    origin: req.headers.origin,
    method: req.method,
    path: req.path,
    headers: req.headers
  });
  next();
});

// 添加代理中间件
app.use('/swagger-api', swaggerProxy);
app.use('/local-api', localApiProxy);

// 添加错误处理中间件
app.use((err, req, res, next) => {
  console.error('Error:', err);
  res.status(500).json({
    error: 'Internal Server Error',
    message: err.message
  });
});

// API 路由
app.use('/api', apiRoutes);

// 添加健康检查端点
app.get('/health', (req, res) => {
  res.json({ status: 'ok' });
});

// 在启动服务器之前检查数据库
db.checkDatabaseState()
  .then(() => {
    app.listen(port, '0.0.0.0', () => {
      console.log(`Server running on port ${port}`);
      console.log(`Server listening on all network interfaces`);
      console.log(`CORS enabled for Docker environment`);
    });
  })
  .catch(err => {
    console.error('Failed to initialize database:', err);
    process.exit(1);
  });